#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include "task.h"

typedef void(*func)();
func tasks[3] = { 0 };

void LoadTask(){
    tasks[0] = PrintLog;
    tasks[1] = Download;
    tasks[2] = PrintOver;
}

void Handler(){
    int i = 0;
    for(; i < 3; i++){
        tasks[i]();
    }
}

void DoOtherThing(){
    Handler();
}

int main(){
    printf("I am a father process, pid: %d, ppid: %d\n", getpid(), getppid());
    pid_t id = fork();
    if(id == 0){
        int cnt = 5;
        while(cnt){
            printf("I am a child process, pid: %d, ppid: %d\n", getpid(), getppid());
            sleep(1);
            cnt--;
        }
        printf("child quit...\n");
        exit(3);
    }
    // load 
    LoadTask();
    while(1){
        int status = 0;
        pid_t rid = waitpid(id, &status, WNOHANG);
        if(rid == 0){
            sleep(1);
            printf("Child is runing, please wait next time\n");
            // ... do other thing
            DoOtherThing();
        }else if(rid > 0){
            if(WIFEXITED(status)){
                printf("wait success!\n");
                printf("child's quit code: %d\n", WEXITSTATUS(status));
            }else{
                printf("quit unnormal\n");
            }
            break;
        }else{
            printf("wait failed\n");
            break;
        }
        
    }
    
    
    
    
    
    
    
    
    
    //sleep(4);
    ////pid_t rid = wait(NULL);
    //int status = 0;
    //pid_t rid = waitpid(id, &status, 0);
    //sleep(2);
    //if(rid > 0){
    //    if(WIFEXITED(status)){
    //        printf("wait sucess!, rid = %d\n", rid);
    //        printf("status: %d, exit code: %d, exit signal: %d\n", status, (status >> 8) & 0XFF, status & 0X7F);
    //    }else{
    //        printf("child quit unnormal!\n");
    //    }
    //}else{
    //    printf("wait failed!\n");
    //}
    //printf("father quit...\n");
    return 0;
}
